<?php
/**
 * 充值操作类
 * Created		: 2012-05-28
 * Modified		: 2012-07-07
 * @version		: 1.0.0
 * @author		: Joseph Chen (chenliq@gmail.com)
 */
class Pay 
{
	/**
	 * 充值记录表
	 * @var string
	 */
	public static $tbl = 'pay_order_log';
	/**
	 * 错误提示信息
	 * @var string
	 */
	public static $msg = '';
	/**
	 * 充值方式列表缓存key
	 * @var string
	 */
	public static $pmlKey = 'paymode-list';
	/**
	 * 充值方式缓存key前缀
	 * @var string
	 */
	public static $pmPreKey = 'paymode:';
	
	/**
	 * 读取一个支付方式信息
	 * @param int $id
	 */
	public static function readPayMode($id) 
	{
		$info = Cache::getHash(self::$pmPreKey.$id);
		if (!$info) {
			$model = new Model('pay_mode');
			$info = $model->read($id);
			if (!$info) {
				return false;
			}
			Cache::setHash(self::$pmPreKey.$id, $info);
		}
		return $info;
	}
	
	/**
	 * 获取支付方式列表
	 * @param int $status
	 * @return array
	 */
	public static function getPayModeList()
	{
		$list = null;
		$idList = Cache::lRange(self::$pmlKey, 0, -1);
		if ($idList) {
			foreach ($idList as $id) 
			{
				$tmp = Cache::getHash(self::$pmPreKey.$id);
				if (!$tmp) {
					$list = null;
					break;
				}
				$list[] = $tmp;
			}
		} 

		if (!$list) {
			$list = self::recacheAllPayMode();
		}
		
		return $list;
	}
	
	/**
	 * 重新缓存所有的支付方式
	 * @return array
	 */
	public static function recacheAllPayMode()
	{
		$model = new Model('pay_mode');
		$order = 'orderid asc,id asc';
		$list = $model->where('status=1')->order($order)->select();
		Cache::delete(self::$pmlKey);
		foreach ($list as $v) {
			if ($v['status']!=1) {
				continue;
			}
			Cache::rPush(self::$pmlKey, $v['id']);
			Cache::setHash(self::$pmPreKey.$v['id'], $v);
		}
		return $list;
	}
	
	/**
	 * 清除过期的待支付订单(默认超过30天)
	 * @param int $expire
	 */
	public static function clearExpirePayOrder($expire=2592000) 
	{
		$commitTime = time() - $expire;
		Db::delete('pay_order_log', 'create_time<='.$commitTime);
		return true;
	}
	
	/**
	 * 充值到游戏
	 * @param unknown_type $orderData
	 */
	public static function pay2game($gameId, $serverId)
	{
		$game = Game::read($gameId);
		$server = Game::readServer($serverId);
		$server_url = 'http://'.$server['domain'];
		$sid = $server['sid'];
		// 充值人民币金额(默认单位:元)
		$money = $orderData['gold_value']/C('RMB_COIN_RATE');
		// 充值金额转成游戏币
		// 充值金额为平台币,转成RMB,再乘以游戏设置的RMB与游戏币的倍率
		$gold = floor($money * $gameInfo['pay_rate']);
		// 游戏联合运营的密钥
		$secret_key = Games::$secret_key[$gameSign];
	
		$user = $orderData['username'];
		$time = time();
		$order = $orderData['order_no'];
		$domain = $gameInfo['domain'];
		$return = false;
		// 测试时只有一个元宝
		$gold = 1;
		switch ($gameSign) {
			// 神仙道
			case 'sxd':
				$sign   = md5($user.'_'.$gold.'_'.$order.'_'.$domain.'_'.$secret_key);
				$url = "http://api.sxd.xd.com/api/buygold.php?user=".$user
						."&gold=".$gold."&order=".$order."&domain=".$domain."&sign=".$sign;
				self::$pay_game_status = @$curl->get($url);
				// 神仙道状态值为1或6,说明也充值成功了
				if (self::$pay_game_status === '1' || self::$pay_game_status === '6') {
					$return = true;
				}
				break;
	
				// 盛世三国
			case 'sssg':
				$sign = md5($user.'_'.$time.'_'.$order.'_'.$gold.'_'.$secret_key) ;
				$url = $server_url."/api/charge?user=".$user."&gold=".$gold."&order=".$order."&time=".$time."&sign=".$sign;
				self::$pay_game_status = @$curl->get($url);
				if (self::$pay_game_status === '1') {
					$return = true;
				}
	
				break;
	
				// 一骑当先
			case 'yqdx':
				$sid = $serverInfo['server_no'];
				$auth = base64_encode('tid='.Games::$yqdxTid.'&sid='.$sid.'&account='.$user
						.'&oid='.$order.'&otype=0&money='.$money
						.'&gold='.$gold.'&ip='.$_SERVER['REMOTE_ADDR'].'&time='.$time);
				$verify = md5($auth.$secret_key);
				$url = "http://up.9787.com/api/1/uinterface.php?action=charge&auth=".$auth."&verify=".$verify;
				$json = @$curl->get($url);
				$res = Json::decode($json);
				self::$pay_game_status = $res->result;
				if (self::$pay_game_status === '1') {
					$return = true;
				}
				break;
	
				// 龙将
			case 'lj':
				$sid = $serverInfo['server_no'];
				$sign = md5($order.$secret_key);
				// 龙将金额单位为"分"
				$money = $money*100;
				$url = 'http://pay.my9yu.com/long/pay/591yo/'.$sid.'/by/username?name='.$user
						.'&money='.$money.'&gold='.$gold.'&coupon=0&coin=0&order='.$order.'&sign='.$sign;
				$json = @$curl->get($url);
				$res = Json::decode($json);
				self::$pay_game_status = $res->code;
				if (self::$pay_game_status == 0 || self::$pay_game_status == -5) {
					self::$pay_game_status = 1;
					$return  = true;
				}
				break;
	
				// 梦幻飞仙
			case 'mhfx':
				$secret_key = Games::$mhfxPayKey;
				$tmp = explode('.', $serverInfo['domain']);
				$sid = $tmp[0];
				$sign = strtolower(md5($user.$sid.$order.$money.$gold.$time.$secret_key)) ;
				$url = $server_url."/api/cmn/pay_sid.php?account=".$user
						."&serverid=".$sid."&coin=".$gold."&rmb=".$money
						."&orderid=".$order."&type=0"."&sign=".$sign."&time=".$time;
				$res = $curl->get($url);
				if ($res === '1') {
					self::$pay_game_status = 1;
					$return  = true;
				} else if (false === $res) {
					self::$pay_game_status = 0;
				} else if (false === 'ERROR-15') {
					self::$pay_game_status = 1;
				} else {
					self::$pay_game_status = substr($res, 6);
				}
				break;
	
				// 未定义游戏接口,无法处理
			default:
				$return = false;
			break;
		}
		return $return;
	}
	
	/**
	 * 生成订单号
	 */
	public static function generateOrderNo()
	{
		switch ($GLOBALS['_orderno_type'])
		{
			case 1:
				$time = explode(' ', microtime());
				return date('YmdHis').substr($time[0], 2).mt_rand(0, 0xffff);
			break;
			
			case 2:
				return sha1(uniqid().Ip::getIp().mt_rand(0, 0xffff));
			break;
			
			case 3:
				return sprintf(
					'%04x%s%04x', 
					mt_rand(0, 0xffff), 
					md5(uniqid().Ip::getIp()), 
					mt_rand(0, 0xffff)
				);
			break;
			
			default:
				return sha1(uniqid().mt_rand(0, 0xffff));
			break;
		}
	}
}
